package com.maozzi.api.mq.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.maozzi.api.mq.properties.MqProperties;
import com.maozzi.api.mq.template.MsgTemplate;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.CompositeMessageConverter;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;

import java.util.List;

/**
 * mq 配置
 *
 * @author maozi
 */
@Configuration
@EnableConfigurationProperties(MqProperties.class)
public class MqConfig {

    @Bean
    public MsgTemplate msgTemplate(RocketMQTemplate template) {
        return new MsgTemplate(template);
    }

    /**
     * 增加Java8 local date支持
     *
     * @return 返回
     */
//    @Bean
//    @Primary
    public RocketMQMessageConverter localDateConverter() {
        RocketMQMessageConverter converter = new RocketMQMessageConverter();
        CompositeMessageConverter messageConverter = (CompositeMessageConverter) converter.getMessageConverter();

        List<MessageConverter> converters = messageConverter.getConverters();
        for (MessageConverter i : converters) {
            if (i instanceof MappingJackson2MessageConverter jackson) {
                ObjectMapper mapper = jackson.getObjectMapper();
                // 增加Java8 local date支持
                mapper.registerModule(new JavaTimeModule());
            }
        }

        return converter;
    }

    @Bean
    @ConditionalOnProperty(name = "rocketmq.mq.enabledIsolation", havingValue = "true")
    public IsolationConfig isolationConfig(MqProperties mqProperties) {
        return new IsolationConfig(mqProperties);
    }
}
